﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using BestCode.Creds.Entities;
using BestCode.Creds.UI.Common;
using BestCode.Creds.UI.Core;
using BestCode.Creds.UI.ViewModel;
using NHibernate.Engine;

namespace BestCode.Creds.UI
{
    public partial class VwFieldDefinition : UserControl
    {
        private VmFieldDefinition viewModel;
        private Window modalWindow;
        private VwEditFieldDefinition modalControl;

        private EntityInfo entityInfo = null;

        private BackgroundWorker bWorker = null;

        public event EventHandler OnShowEnabledFieldsReport;

        
        public VwFieldDefinition()
        {
            InitializeComponent();
            Loaded += VwFieldDefinition_Loaded;
        }

        void VwFieldDefinition_Loaded(object sender, RoutedEventArgs e)
        {
            txtFilter.KeyDown += txtFilter_KeyDown;
        }

        void txtFilter_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                viewModel.SearchByFilter(txtFilter.Text);
                txtFilter.SelectAll();
                txtFilter.Focus();
            }
        }

        

        public void SetViewModel(EntityInfo entity)
        {
            entityInfo = entity;
            viewModel = new VmFieldDefinition(entityInfo);
            this.DataContext = viewModel;
        }

        private void Control_OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            var grid = sender as DataGrid;
            var field = grid.SelectedItem as FieldDefinition;
            ShowModalWindow(field);

        }

        void modalControl_OnCloseControl(object sender, EventArgs e)
        {
            modalWindow.Close();
        }
        
        private void ImageButton_Click(object sender, RoutedEventArgs e)
        {
            FieldDefinition field = new FieldDefinition();
            field.Entity = entityInfo;
            ShowModalWindow(field);
        }

        private void ShowModalWindow(FieldDefinition field)
        {
            modalControl = new VwEditFieldDefinition(field);
            modalControl.OnCloseControl += modalControl_OnCloseControl;
            modalWindow = new Window
            {
                Title = "New",
                Content = modalControl,
                Height = 565,
                Width = 600,
                AllowsTransparency = true,
                WindowStartupLocation = WindowStartupLocation.CenterOwner,
                WindowStyle = WindowStyle.None,

                //SizeToContent = SizeToContent.WidthAndHeight,
                ResizeMode = ResizeMode.NoResize
            };

            modalWindow.Owner = WindowUtil.GetParentWindow(this);
            WindowUtil.ApplyEffect(WindowUtil.GetParentWindow(this));
            modalWindow.ShowDialog();
            WindowUtil.ClearEffect(WindowUtil.GetParentWindow(this));
        }


        private void btnGenerate_Click(object sender, RoutedEventArgs e)
        {
            bWorker = new BackgroundWorker();
            bWorker.WorkerReportsProgress = true;
            bWorker.DoWork += (o, ea) =>
            {
                
                Dispatcher.Invoke(() =>
                {
                    grdMain.IsEnabled = false;
                });

                try
                {
                    var generator = new CredentialGenerator();
                    generator.onCredentialGenerated += generator_onCredentialGenerated;
                    generator.Do(viewModel.Items);
                }
                catch (Exception exe)
                {
                    Dispatcher.Invoke(() =>
                    {
                        MessageBox.Show(exe.Message);
                    });
                }
                
            };

            bWorker.RunWorkerCompleted += (o, ea) => Dispatcher.Invoke(() =>
            {
                grdMain.IsEnabled = true;
            });


            bWorker.ProgressChanged += (o, ea) => Dispatcher.Invoke(() =>
            {
                pgbar.Value = ea.ProgressPercentage;
            });
            bWorker.RunWorkerAsync();
        }

        void generator_onCredentialGenerated(object sender, EventArgs e)
        {
            bWorker.ReportProgress((int)sender);
        }


        private void btnGenerateSelectedItems_Click(object sender, RoutedEventArgs e)
        {
            if (grdFieldDefinition.SelectedItems == null || grdFieldDefinition.SelectedItems.Count == 0)
            {
                throw  new Exception("Without Selection");
                return;
            }


            var generator = new CredentialGenerator();

            var collection = new ObservableCollection<FieldDefinition>();
            foreach (var item in grdFieldDefinition.SelectedItems)
            {
                collection.Add((FieldDefinition)item);
            }

            generator.Do(collection);
        }

        private void btnOpenOutputFolder_Click(object sender, RoutedEventArgs e)
        {
           OpenWinFolderExplorer(viewModel.OutputFolder);
        }

        private void btnOpenPicturesFolder_Click(object sender, RoutedEventArgs e)
        {
            OpenWinFolderExplorer(viewModel.PicturesFolder);
        }

        public void OpenWinFolderExplorer(string path)
        {
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo.UseShellExecute = true;
            process.StartInfo.FileName = @"explorer";
            process.StartInfo.Arguments = path;
            process.Start();
        }

        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            if (viewModel.SelectedItem != null)
                viewModel.Delete(viewModel.SelectedItem);
        }

        private void BtnShowEnabledFieldsReport_OnClick(object sender, RoutedEventArgs e)
        {
            if (OnShowEnabledFieldsReport != null)
            {
                OnShowEnabledFieldsReport(viewModel.SelectedEntityChild, EventArgs.Empty);
            }
        }
    }
}
